package com.food.restaurantpro.fragments;

import java.util.Observable;
import java.util.Observer;

import com.food.restaurantpro.R;
import com.food.restaurantpro.RestaurantApp;
import com.food.restaurantpro.activity.MainActivity;
import com.food.restaurantpro.connection.DataHelper;
import com.food.restaurantpro.connection.DataResult;
import com.food.restaurantpro.connection.IServerService.Methods;
import com.food.restaurantpro.imageloader.ImageLoader;
import com.food.restaurantpro.managingnetwork.ManagingNetwork;
import com.food.restaurantpro.objects.UserInfo;
import com.food.restaurantpro.utils.AlertDialogInterface;
import com.food.restaurantpro.utils.AlertDialogManager;
import com.food.restaurantpro.utils.Utils;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class LoginFragment extends Fragment implements OnClickListener {
	private boolean isProcessLogin = false;
	private boolean isProcessUpdate = false;
	private TextView tvHeader;
	private EditText mEtUserKey;
	private TextView mTvMemberName;
	private TextView mTvCodeNumber;
	private TextView mTvEmail;
	private TextView mTvPhone;
	private TextView mTvAddress;
	private TextView mEtEmail;
	private TextView mEtPhone;
	private TextView mEtAddress;
	private RelativeLayout mRlSignout;
	private RelativeLayout mRlControl;
	private ImageLoader mImageLoader;
	private ImageView mIvAvatar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mImageLoader = new ImageLoader(getActivity(),
				R.drawable.membership_avatar, 0);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_login, container, false);
		tvHeader = (TextView) view.findViewById(R.id.tvHeader);
		mEtUserKey = (EditText) view.findViewById(R.id.edtUserKey);
		mTvMemberName = (TextView) view.findViewById(R.id.tvMemberName);
		mTvCodeNumber = (TextView) view.findViewById(R.id.tvCodeNumber);
		mTvEmail = (TextView) view.findViewById(R.id.tvEmail);
		mTvPhone = (TextView) view.findViewById(R.id.tvPhone);
		mTvAddress = (TextView) view.findViewById(R.id.tv_Address);
		mEtEmail = (TextView) view.findViewById(R.id.edtEmail);
		mEtPhone = (TextView) view.findViewById(R.id.edtPhone);
		mEtAddress = (TextView) view.findViewById(R.id.edtAddress);
		mRlControl = (RelativeLayout) view.findViewById(R.id.rl_control);
		mRlSignout = (RelativeLayout) view.findViewById(R.id.rl_signout);
		mIvAvatar = (ImageView) view.findViewById(R.id.imgv_membership_avatar);
		view.findViewById(R.id.btnSubmitLogin).setOnClickListener(this);
		view.findViewById(R.id.tvSubmitLogin).setOnClickListener(this);
		view.findViewById(R.id.btnCancelLogin).setOnClickListener(this);
		view.findViewById(R.id.tvYourCodeReservationGuest).setOnClickListener(
				this);
		view.findViewById(R.id.tvPeopleExpandItemReservation)
				.setOnClickListener(this);
		view.findViewById(R.id.tvCancelLogin).setOnClickListener(this);
		mRlSignout.setOnClickListener(this);
		view.findViewById(R.id.imgvEmailEdt).setOnClickListener(this);
		view.findViewById(R.id.imgvPhoneEdit).setOnClickListener(this);
		view.findViewById(R.id.imgvAddressEdit).setOnClickListener(this);
		view.findViewById(R.id.btnConfirm).setOnClickListener(this);
		view.findViewById(R.id.btnCancel).setOnClickListener(this);

		if (RestaurantApp.userInfo != null
				&& !RestaurantApp.userInfo.getUserId().equals("")) {
			showUserDetail(view);
		} else {
			showLogin(view);
		}
		return view;
	}

	@Override
	public void onDestroy() {
		// TODO delete image and cache de giai phong bo nho
		super.onDestroy();
		if (mImageLoader != null) {
			mImageLoader.clearMemoryCache();
		}
		Runtime.getRuntime().gc();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnSubmitLogin:
		case R.id.tvSubmitLogin:
			doLogin();
			break;
		case R.id.btnCancelLogin:
		case R.id.tvCancelLogin:
			getActivity().finish();
			break;
		case R.id.rl_signout:
			doLogout();
			break;
		case R.id.imgvEmailEdt:
			mEtEmail.setVisibility(View.VISIBLE);
			mEtEmail.setText(mTvEmail.getText().toString());
			mEtEmail.requestFocus();
			mTvEmail.setVisibility(View.INVISIBLE);
			mRlControl.setVisibility(View.VISIBLE);
			mRlSignout.setVisibility(View.GONE);
			break;
		case R.id.imgvPhoneEdit:
			mEtPhone.setVisibility(View.VISIBLE);
			mEtPhone.setText(mTvPhone.getText().toString());
			mEtPhone.requestFocus();
			mTvPhone.setVisibility(View.INVISIBLE);
			mRlControl.setVisibility(View.VISIBLE);
			mRlSignout.setVisibility(View.GONE);
			break;
		case R.id.imgvAddressEdit:
			mEtAddress.setVisibility(View.VISIBLE);
			mEtAddress.setText(mTvAddress.getText().toString());
			mEtAddress.requestFocus();
			mTvAddress.setVisibility(View.INVISIBLE);
			mRlControl.setVisibility(View.VISIBLE);
			mRlSignout.setVisibility(View.GONE);
			break;
		case R.id.btnCancel:
		case R.id.tvPeopleExpandItemReservation:
			cancelEdit();
			break;
		case R.id.btnConfirm:
		case R.id.tvYourCodeReservationGuest:
			doUpdate();
			break;
		default:
			break;
		}
	}

	private void cancelEdit() {
		mEtAddress.setVisibility(View.GONE);
		mEtEmail.setVisibility(View.GONE);
		mEtPhone.setVisibility(View.GONE);
		mTvAddress.setVisibility(View.VISIBLE);
		mTvEmail.setVisibility(View.VISIBLE);
		mTvPhone.setVisibility(View.VISIBLE);
		mRlControl.setVisibility(View.GONE);
		mRlSignout.setVisibility(View.VISIBLE);
	}

	private void doUpdate() {
		if (isProcessUpdate) {
			return;
		}
		isProcessUpdate = true;
		boolean needUpdate = false;
		if (mEtEmail.getVisibility() == View.VISIBLE
				&& Utils.isValidEmail(mEtEmail.getText().toString())) {
			needUpdate = true;
			RestaurantApp.userInfo.setCustomerEmail(mEtEmail.getText()
					.toString());
		}
		if (mEtPhone.getVisibility() == View.VISIBLE) {
			needUpdate = true;
			RestaurantApp.userInfo.setCustomerPhone(mEtPhone.getText()
					.toString());
		}
		if (mEtAddress.getVisibility() == View.VISIBLE) {
			needUpdate = true;
			RestaurantApp.userInfo.setCustomerAddress(mEtAddress.getText()
					.toString());
		}
		if (!needUpdate) {
			isProcessUpdate = false;
			return;
		}
		DataHelper.getInstance().addObserver(new Observer() {
			@Override
			public void update(Observable observable, Object data) {
				// TODO Auto-generated method stub
				DataResult result = (DataResult) data;
				if (result.getMethodName().equals(Methods.updateUserInfo)) {
					((MainActivity) getActivity()).hideProcessDialog();
					String status = (String) result.getData();
					if (!Utils.isEmpty(status) && status.equals("true")) {
						UserInfo.saveCurrentUserInfo(RestaurantApp.userInfo);
						cancelEdit();
						showUserDetail(getView());
						Utils.showToast("Update succesfull");
					} else {
						RestaurantApp.userInfo = UserInfo.getCurrentUserInfo();
						cancelEdit();
						showUserDetail(getView());
						Utils.showToast("Update fail");
					}
					isProcessUpdate = false;
					DataHelper.getInstance().deleteObserver(this);
				}
			}
		});
		((MainActivity) getActivity()).showProcessDialog();
		DataHelper.getInstance().updateUserInfo(RestaurantApp.userInfo);
	}

	private void doLogout() {
		RestaurantApp.userInfo = UserInfo.removeCurrentUserInfo();
		Utils.showToast("Logout successfull");
		showLogin(getView());
	}

	private void doLogin() {
		if (ManagingNetwork.isNetworkAvailable()) {
			if (isProcessLogin) {
				return;
			}
			isProcessLogin = true;
			String userKey = mEtUserKey.getText().toString();
			if (Utils.isEmpty(userKey)) {
				Utils.showToast("Please input user code");
				isProcessLogin = false;
				return;
			}
			DataHelper.getInstance().addObserver(new Observer() {
				@Override
				public void update(Observable observable, Object data) {
					// TODO Auto-generated method stub
					DataResult result = (DataResult) data;
					if (result.getMethodName().equals(Methods.login)) {
						((MainActivity) getActivity()).hideProcessDialog();
						UserInfo userInfo = (UserInfo) result.getData();
						if (userInfo != null
								&& !Utils.isEmpty(userInfo.getUserId())) {
							UserInfo.saveCurrentUserInfo(userInfo);
							RestaurantApp.userInfo = userInfo;
							showUserDetail(getView());
							Utils.showToast("Login succesfull");
						} else {
							Utils.showToast("Login fail");
						}
						isProcessLogin = false;
						DataHelper.getInstance().deleteObserver(this);
					}
				}
			});
			((MainActivity) getActivity()).showProcessDialog();
			DataHelper.getInstance().login(userKey);
		} else {

			AlertDialogManager.showAlertDialog(getActivity(),
					new AlertDialogInterface() {

						@Override
						public void onChooseYesCallback() {
							// TODO Auto-generated method stub
						}

						@Override
						public void onChooseNoCallback() {
							// TODO Auto-generated method stub

						}
					}, false, true, RestaurantApp.CURRENT_CONTEXT
							.getString(R.string.title_internet_error),
					RestaurantApp.CURRENT_CONTEXT
							.getString(R.string.NETWORK_ERROR),
					RestaurantApp.CURRENT_CONTEXT.getString(R.string.ok), "",
					false);

		}
	}

	private void showUserDetail(View view) {
		view.findViewById(R.id.rl_login).setVisibility(View.GONE);
		view.findViewById(R.id.rl_details).setVisibility(View.VISIBLE);
		tvHeader.setText(getActivity().getString(R.string.tvMembership_Title));
		if (RestaurantApp.userInfo == null) {
			return;
		}
		if (!Utils.isEmpty(RestaurantApp.userInfo.getCustomerAvataURL())) {
			mImageLoader.displayImage(
					RestaurantApp.userInfo.getCustomerAvataURL(), mIvAvatar);
		}
		mTvMemberName.setText(RestaurantApp.userInfo.getCustomerName());
		mTvCodeNumber.setText(RestaurantApp.userInfo.getGenerateId());
		mTvEmail.setText(RestaurantApp.userInfo.getCustomerEmail());
		mTvPhone.setText(RestaurantApp.userInfo.getCustomerPhone());
		mTvAddress.setText(RestaurantApp.userInfo.getCustomerAddress());
	}

	private void showLogin(View view) {
		tvHeader.setText(getActivity().getString(R.string.sign_in));
		view.findViewById(R.id.rl_details).setVisibility(View.GONE);
		view.findViewById(R.id.rl_login).setVisibility(View.VISIBLE);
	}
}
